import { login, getInfo } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  setUserData,
} from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    historyRouter: [],
    activeRouter: '',
    isHanleRoutes: false,
    routeSubTitle: '',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  ADD_HISTORY_ROUTER(state, playload) {
    const index = state.historyRouter.findIndex(item => item.route === playload.route)
    index === -1 && state.historyRouter.push(playload)
  },
  // 删除TABS
  DELETE_HISTORY_ROUTER(state, route) {
    let index = 0
    for (const option of state.historyRouter) {
      if (option.route === route) {
        break
      }
      index++
    }
    state.historyRouter.splice(index, 1)
  },
  // 设置当前激活的tab
  SET_ACTIVE_ROUTER(state, index) {
    state.activeRouter = index
  },
  SET_IS_HANDLE_ROUTER(state, playload) {
    state.isHanleRoutes = playload
  },
  SET_ROUTER_SUBTITLE(state, playload) {
    state.routeSubTitle = playload
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password, requestSourceEnum } = userInfo
    return new Promise((resolve, reject) => {
      const setData = { account: account.trim(), password: password }

      login(setData, requestSourceEnum)
        .then(response => {
          window.sessionStorage.setItem('userId', response.userVo.id)
          const data = response

          setToken(data.token)
          data && setUserData(data)

          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  // 通过token来查询用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      console.log('getinfo start')
      getInfo(state.token)
        .then(data => {
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          const { nickName } = data
          commit('SET_NAME', nickName)
          resolve(data)
        })
        .catch(error => {
          console.log('getinfo')
          reject(error)
        })
    })
  },

  // user logout 退出登录
  logout({ commit, state }, isReLoad = true) {
    return new Promise((resolve, reject) => {
      console.log('out start')
      removeToken()
      console.log('resetRouter')
      resetRouter()
      commit('RESET_STATE')
      resolve()
      // isReLoad && location.reload()
      // isReLoad && (window.location.href = 'http://szls.chiefdata.net/cloud-platform_nologin.html')

      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   console.log('out error')
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
